<template>
  <el-card class="box-card">
    <!-- 卡片顶部按钮 -->
    <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
    <!-- 表格组件，展示已有品牌数据 -->
    <el-table style="margin: 10px 0px" border :data="trademarkArr">
      <!--                                                       每行对应编号 -->
      <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
      <el-table-column label="品牌名称">
        <!-- 插槽 -->
        <!-- 下面这个是用来不报错，否则声明了$index但不用会一直报红 -->
        <!-- eslint-disable -->
        <template #="{ row, $index }">
          <h1>{{ row.tmName }}</h1>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <!-- 修改按钮 -->
          <el-button type="primary" icon="Edit" @click="updateTrademark(row)"></el-button>
          <!-- 删除按钮 -->
          <el-popconfirm :title="`确定要删除${row.tmName}?`" @confirm="removeTrademark(row.id)">
            <template #reference>
              <el-button type="primary" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
        <!-- eslint-enable -->
      </el-table-column>
    </el-table>
    <!-- 分页器组件 -->
    <!-- 有v-model的不能简写，否则不显示 -->
    <!-- 两个自定义事件都是pagination定义的事件，按相应按钮就会触发（改变页数、改变每页呈现数据条数） -->
    <el-pagination
      @current-change="changePageNo"
      @size-change="sizeChange"
      v-model:current-page.sync="pageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next,jumper,->,sizes,total"
      :total="total"
    ></el-pagination>
  </el-card>
  <!-- 对话框组件，添加或删除产品时弹出 -->
  <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改产品' : '添加产品'">
    <!-- 加上model用来对表单数据进行表单校验 -->
    <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
      <!-- 品牌名称 -->
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input placeholder="请输入产品名称" v-model="trademarkParams.tmName"></el-input>
      </el-form-item>
      <!-- 品牌LOGO -->
      <!-- action是上传图片的url,前面要加/api，否则代理服务器不会工作 -->
      <!--  -->
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 具名插槽:footer -->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark/index'
import { TradeMarkList, TradeMarkResponseData, TradeMark } from '@/api/product/trademark/type'
//引入UploadProps的类型，跟upload有关
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
//当前页码
let pageNo = ref<number>(3)
//每页展示数据
let limit = ref<number>(3)
//已有品牌数据总数
let total = ref<number>()
//存储已有品牌的数据
let trademarkArr = ref<TradeMarkList>([])
//决定对话框是否出现
let dialogFormVisible = ref<boolean>(false)
//定义手机新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
//获取el-form组件实例，用于表单校验
let formRef = ref()
//获取已有产品数据
const getHasTrademark = async () => {
  let result: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value)
  if (result.code === 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.tradeMarkList
  }
}
//页数改变时调用，根据当前pageNo和limit再请求一次数据
const changePageNo = () => {
  getHasTrademark()
}
//改变每页显示产品个数时，同上
const sizeChange = () => {
  pageNo.value = 1
  getHasTrademark()
}
//添加品牌 按钮的回调
const addTrademark = () => {
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  trademarkParams.id = 0
  //ts的问号语法，如果formRef有value就调用，没有就不调用
  //清除上一次的表单校验结果
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
  dialogFormVisible.value = true
}
//修改品牌 按钮的回调
const updateTrademark = (row: TradeMark) => {
  Object.assign(trademarkParams, row) //ES6语法，作用同下面一样
  // trademarkParams.tmName= row.tmName
  // trademarkParams.logoUrl= row.logoUrl
  // trademarkParams.id = row.id
  //ts的问号语法，如果formRef有value就调用，没有就不调用
  //清除上一次的表单校验结果
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
  dialogFormVisible.value = true
}
//对话框底部取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}
//对话框底部确定按钮
const confirm = async () => {
  //表单校验,校验成功后再进行下面的行为
  await formRef.value.validate()
  // 添加或修改
  let result = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '添加品牌成功',
    })
    // 修改就保持在原地，添加就跳转回第一页
    pageNo.value = trademarkParams.id ? pageNo.value : 1
    getHasTrademark()
  } else {
    ElMessage({
      type: 'error',
      message: '添加品牌失败',
    })
  }

  dialogFormVisible.value = false
}
//upload组件，上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //上传文件成功之前，可以用来约束文件的大小
  //要求：文件格式 png|jpg|gif 大小 <= 4M
  if (
    rawFile.type === 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小应小于4M',
      })
      return false
    }
  } else {
    //element-plus中的提示组件
    ElMessage({
      type: 'error',
      message: '文件格式应改为PNG|JPG|GIF',
    })
    return false
  }
}
//upload组件，图片上传成功后触发的钩子函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  // uploadFile,
) => {
  //response 当前这次上传图片post请求服务器返回的数据
  //uploadFile
  //收集图片的url，用于将来新增品牌数据
  trademarkParams.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}
//品牌校验自定义校验规则
//                     规则      文本内容     放行函数
const validatorTmName = (rule: any, value: any, callBack: any) => {
  rule //只是写一下防报错，没任何作用
  if (value.length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌位数应该大于2位'))
  }
}
//品牌logo校验自定义校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  rule //只是写一下防报错，没任何作用
  console.log(value)
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片不能为空'))
  }
}
//气泡确认框确定按钮的回调
const removeTrademark = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  console.log(result)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    pageNo.value = trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1
    getHasTrademark()
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
//表单校验规则对象
const rules = {
  //                                     自定义的规则校验函数
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, trigger: 'change', validator: validatorLogoUrl }],
}
onMounted(() => {
  getHasTrademark()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
